package com.github.ylt.protocol.http;

import lombok.SneakyThrows;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * 扩展http1.1的协议使其支持SUBSCRIBE, UNSUBSCRIBE，NOTIFY请求
 */
public class HttpServer extends Thread implements Runnable{
    private final ServerSocketChannel serverSocketChannel;
    private final Selector selector;

    public HttpServer(int port) throws IOException {
        selector = Selector.open();
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress(port));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }


    @SneakyThrows
    @Override
    public void run(){
        while (!this.isInterrupted()){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                if (key.isAcceptable()){
                    SocketChannel client = serverSocketChannel.accept();
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_READ);
                    new HttpServerRead(client,key).read();
                }else if(key.isReadable()){
                    SocketChannel client = (SocketChannel) key.channel();
                    new HttpServerRead(client,key).read();
                }
                iterator.remove();
            }
        }
    }

    private SocketChannel accept() throws IOException {
        return serverSocketChannel.accept();
    }
}
